package org.dromara.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.app.appParams.AppDetailByIdParams;
import org.dromara.app.appParams.AppPingLunpageParams;
import org.dromara.app.appParams.AppPlingLunParams;
import org.dromara.app.appReturn.AppYueJuPingLunReturn;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.domain.SkAppUser;
import org.dromara.app.domain.SkUserTrends;
import org.dromara.app.mapper.SkAppUserMapper;
import org.dromara.app.mapper.SkUserTrendsMapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkDongtaiPinglunBo;
import org.dromara.app.domain.vo.SkDongtaiPinglunVo;
import org.dromara.app.domain.SkDongtaiPinglun;
import org.dromara.app.mapper.SkDongtaiPinglunMapper;
import org.dromara.app.service.ISkDongtaiPinglunService;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 动态评论信息Service业务层处理
 *
 * @author Evacuation
 * @date 2024-09-23
 */
@RequiredArgsConstructor
@Service
public class SkDongtaiPinglunServiceImpl implements ISkDongtaiPinglunService {

    private final SkDongtaiPinglunMapper baseMapper;

    private final SkAppUserMapper skAppUserMapper;

    private final SkUserTrendsMapper skUserTrendsMapper;

    /**
     * 查询动态评论信息
     *
     * @param id 主键
     * @return 动态评论信息
     */
    @Override
    public SkDongtaiPinglunVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询动态评论信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 动态评论信息分页列表
     */
    @Override
    public TableDataInfo<SkDongtaiPinglunVo> queryPageList(SkDongtaiPinglunBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkDongtaiPinglun> lqw = buildQueryWrapper(bo);
        Page<SkDongtaiPinglunVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的动态评论信息列表
     *
     * @param bo 查询条件
     * @return 动态评论信息列表
     */
    @Override
    public List<SkDongtaiPinglunVo> queryList(SkDongtaiPinglunBo bo) {
        LambdaQueryWrapper<SkDongtaiPinglun> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkDongtaiPinglun> buildQueryWrapper(SkDongtaiPinglunBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SkDongtaiPinglun> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), SkDongtaiPinglun::getContent, bo.getContent());
        lqw.eq(bo.getUserId() != null, SkDongtaiPinglun::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), SkDongtaiPinglun::getNickName, bo.getNickName());
        lqw.eq(StringUtils.isNotBlank(bo.getHeadImage()), SkDongtaiPinglun::getHeadImage, bo.getHeadImage());
        lqw.eq(StringUtils.isNotBlank(bo.getAge()), SkDongtaiPinglun::getAge, bo.getAge());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), SkDongtaiPinglun::getSex, bo.getSex());
        lqw.eq(bo.getDongtaiId() != null, SkDongtaiPinglun::getDongtaiId, bo.getDongtaiId());
        return lqw;
    }

    /**
     * 新增动态评论信息
     *
     * @param bo 动态评论信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkDongtaiPinglunBo bo) {
        SkDongtaiPinglun add = MapstructUtils.convert(bo, SkDongtaiPinglun.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改动态评论信息
     *
     * @param bo 动态评论信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkDongtaiPinglunBo bo) {
        SkDongtaiPinglun update = MapstructUtils.convert(bo, SkDongtaiPinglun.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkDongtaiPinglun entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除动态评论信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 评论动态
     *
     * @param params
     * @param req
     */
    @Override
    public void commentYueJu(AppPlingLunParams params, HttpServletRequest req) {
        SkAppUser skAppUser = skAppUserMapper.selectById(CssUtils.getUserId(req));
        SkDongtaiPinglun sk = new SkDongtaiPinglun();
        sk.setUserId(skAppUser.getId());
        sk.setDongtaiId(params.getId());
        sk.setContent(params.getTitle());
        sk.setHeadImage(skAppUser.getHeadImage());
        sk.setNickName(skAppUser.getNickName());
        sk.setSex(skAppUser.getSex());
        if (skAppUser.getBirthday() != null && !skAppUser.getBirthday().equals("")) {
            LocalDate bir = LocalDate.parse(skAppUser.getBirthday() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            Period age = Period.between(bir, LocalDate.now());
            sk.setAge(age.getYears() + "");
        }
        baseMapper.insert(sk);
//        skUserTrendsMapper.update()
        UpdateWrapper<SkUserTrends> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", params.getId())
            .setSql("common_num=common_num+1");
        skUserTrendsMapper.update(updateWrapper);

    }

    /**
     * 评论动态列表
     *
     * @param params
     * @param req
     */
    @Override
    public List<AppYueJuPingLunReturn> getCommentYueJuList(AppPingLunpageParams params, HttpServletRequest req) {
        Long pageNum = (params.getPageNum() - 1) * params.getPageSize();
        List<SkDongtaiPinglun> list = baseMapper.selectList(
            new QueryWrapper<SkDongtaiPinglun>().lambda()
                .eq(SkDongtaiPinglun::getDongtaiId, params.getId())
                .orderByDesc(SkDongtaiPinglun::getCreateTime)
                .last("limit " + pageNum + "," + params.getPageSize())
        );
        List<AppYueJuPingLunReturn> all = BeanUtil.copyToList(list, AppYueJuPingLunReturn.class);
        return all;
    }

    /**
     * 点赞动态
     *
     * @param params
     * @param req
     */
    @Override
    public void dongtaiLikes(AppDetailByIdParams params, HttpServletRequest req) {
        SkUserTrends skUserTrends = skUserTrendsMapper.selectById(params.getId());
        //判断是否存在
        if (skUserTrends.getLikeUserIds() == null) {
            skUserTrends.setLikeUserIds(CssUtils.getUserId(req) + "");
            skUserTrends.setLikeNum(skUserTrends.getLikeNum() + 1);
        } else {
            String[] array = skUserTrends.getLikeUserIds().split(",");
            boolean contains = Arrays.asList(array).contains(CssUtils.getUserId(req) + "");
            if (contains) {
                //包含  取消点赞
                array = removeElement(array, CssUtils.getUserId(req) + "");
                skUserTrends.setLikeUserIds(String.join(",", array));
                if (skUserTrends.getLikeNum() > 0) {
                    skUserTrends.setLikeNum(skUserTrends.getLikeNum() - 1);
                }
            } else {
                //不包含，点赞
                skUserTrends.setLikeUserIds(skUserTrends.getLikeUserIds() + "," + CssUtils.getUserId(req) + "");
                skUserTrends.setLikeNum(skUserTrends.getLikeNum() + 1);
            }
        }
        skUserTrendsMapper.updateById(skUserTrends);
    }

    public static String[] removeElement(String[] array, String toRemove) {
        List<String> list = new ArrayList<>(Arrays.asList(array));
        list.removeIf(toRemove::equals);
        return list.toArray(new String[0]);
    }

}
